package com.fangdd.logtrace.async;

import com.fangdd.logtrace.TraceId;
import com.fangdd.logtrace.TraceIdThreadLocal;
import com.fangdd.logtrace.TraceWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;

/**
 * Created by sulong on 16-9-7.
 */
public class TraceRunnable implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(TraceRunnable.class);

    private TraceId traceId;
    private Runnable inner;

    public TraceRunnable(Runnable real) {
        this(real, TraceIdThreadLocal.concurrentNext());
    }

    public TraceRunnable(Runnable real, TraceId traceId) {
        this.inner = real;
        this.traceId = traceId;
    }

    @Override
    public void run() {
        try {
            TraceWith.run(traceId, new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    try {
                        inner.run();
                    } catch (RuntimeException e) {
                        LOGGER.error("", e);
                        throw e;
                    } catch (Exception t) {
                        LOGGER.error("", t);
                        throw t;
                    }
                    return null;
                }
            });
        } catch (Exception e) {
            LOGGER.error("", e);
        }
    }
}
